package com.yiwyn;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class WordCountSteamDemo {

    public static void main(String[] args) throws Exception {
        //刘流出执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.readTextFile("flink-demo/input/test.txt")
                //处理原文本
                .flatMap((String value, Collector<Tuple2<String, Integer>> out) -> {
                    String[] s = value.split(" ");
                    for (String word : s) {
                        out.collect(Tuple2.of(word, 1));
                    }
                })
                //范型擦除处理
                .returns(Types.TUPLE(Types.STRING, Types.INT))
                //聚合数据 求和
                .keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
                    @Override
                    public String getKey(Tuple2<String, Integer> value) throws Exception {
                        return value.f0;
                    }
                }).sum(1)
                //输出内容
                .print();
        //启动
        env.execute();
    }
}
